package com.jmlee.controller;

import com.jmlee.avo.ChooseSelectVo;
import com.jmlee.avo.CouponVo;
import com.jmlee.component.HostHolder;
import com.jmlee.pojo.*;
import com.jmlee.service.CouponService;
import com.jmlee.util.JSONUtil;
import org.apache.ibatis.session.RowBounds;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.UUID;

/**
 * @author： 郑锦涛
 * @data： 2021/3/20 14:29
 * @version：1.0
 * @描述： 优惠券控制层
 */
@Controller
public class CouponController {

    @Autowired
    CouponService couponService;

    @Autowired
    HostHolder hostHolder;

    @RequestMapping("/goToCoupon")
    public String goToCoupon(){
        return "couponManage";
    }

    /**
     * 日志
     */
    private Logger LOGGER = LoggerFactory.getLogger(CouponController.class);



    SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd");

    /**
     * 获取配置文件里的数据
     * 从配置properties文件中读取default.path.upload的值。
     */
    @Value("${default.path.upload}")
    private String uploadPath;


    /**
     * 广告列表查询
     * @param couponVo
     * @param request
     * @return
     */
    @RequestMapping("/couponTable")
    @ResponseBody
    public String couponTable( CouponVo couponVo, HttpServletRequest request){
        String pageStr = request.getParameter("page");
        String limitStr = request.getParameter("limit");


        Integer x = Integer.valueOf(pageStr).intValue();
        Integer y = Integer.valueOf(limitStr).intValue();

        Integer page = (x-1)*y;
        Integer limit = y;
        RowBounds rowBounds = new RowBounds(page,limit);

        PageBean pageBean =new PageBean();
        List<ACoupon> list = couponService.couponTable(couponVo,rowBounds);
        Integer count = couponService.couponTableCount(couponVo);
        pageBean.setCode(0);
        pageBean.setMsg("");
        pageBean.setCount(count);
        pageBean.setData(list);


        return JSONUtil.objectToJson(pageBean);
    }

    /**
     * 新增优惠券
     * @param aCoupon
     * @return
     */
    @RequestMapping("/couponAdd")
    @ResponseBody
    public ResultCode couponAdd(ACoupon aCoupon){
        if (couponService.couponAdd(aCoupon) > 0){
            return ResultCode.SUCCESS;
        }
        return ResultCode.FAILED;

    }

    /**
     * 获取二级联动的值
     * @param type
     * @return
     */
    @RequestMapping("/getCatId")
    @ResponseBody
    public List<ChooseSelectVo> getCatId(String type){
        //当传回的值为1，即商品，则执行查询商品的service
        if (type.equals("1")){
            return couponService.getItem();
        }
        //当传回的值为2，即商品类型，则执行查询商品类型的service
        if (type.equals("2")){
            return couponService.getCatId();
        }
        return null;
    }

    /**
     *  广告提交后，同时传入数据和文件信息
     * @param acarousel
     * @param file
     * @return
     */
    @RequestMapping("/carouselUpload")
    @ResponseBody
    public String carouselUpload(Acarousel acarousel,MultipartFile file){

        Admin admin = hostHolder.getAdmin();

        // 比如：/static/upload/2021/03/12/cf13891e-4b95-4000-81eb-b6d70ae44930.png
        String format = sdf.format(new Date());
        File folder = new File(uploadPath + format);
        if (!folder.isDirectory()) {
            folder.mkdirs();
        }

        // 对上传的文件重命名，避免文件重名
        String oldName = file.getOriginalFilename();
        String newName = UUID.randomUUID().toString()
                + oldName.substring(oldName.lastIndexOf("."), oldName.length());
        try {
            // 文件保存
            file.transferTo(new File(folder, newName));

            // 返回上传文件的访问路径,指定nginx的代理路径
            String filePath = "http://47.99.200.116/" + format + "/" + newName;

            //将文件路径存入acarousel中
            acarousel.setImageUrl(filePath);
            acarousel.setAdminId(admin.getId());
            //判断是否插入成功
            Integer upload = couponService.carouselUpload(acarousel);
            if (upload > 0){
                return "提交成功";
            }

        } catch (IOException e) {
            e.printStackTrace();
            return "网络异常";
        }


        return null;
    }

    /**
     * 设置每天凌晨1点执行一次
     */
    @Scheduled(cron = "0 0 1 * * ?")
    public void checkCarouselStatus(){
        Boolean check = couponService.checkCarouselStatus();
        if (check){
            LOGGER.info("检查广告");
        }
    }


}
